import java.util.HashMap;
import java.util.Map;

public class Solution337 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int rob(TreeNode root) {
        Map<TreeNode,Integer> f=new HashMap<>();
        Map<TreeNode,Integer> g=new HashMap<>();
        f.put(null,0);
        g.put(null,0);
        dfs(root,f,g);
        return Math.max(f.get(root),g.get(root));
    }

    private void dfs(TreeNode root, Map<TreeNode, Integer> f, Map<TreeNode, Integer> g) {
        if (root==null){
            return;
        }
        dfs(root.left,f,g);
        dfs(root.right,f,g);
        f.put(root,root.val+g.get(root.left)+g.get(root.right));
        g.put(root,Math.max(f.get(root.left),g.get(root.left))+Math.max(f.get(root.right),g.get(root.right)));
    }

    public static void main(String[] args) {
        System.out.println(new Solution337().rob(new TreeNode(3,new TreeNode(2,null,new TreeNode(3)),new TreeNode(3,null,new TreeNode(1)))));
    }
}
